package com.dempe.forest.admin.controller;

import com.dempe.forest.common.discovery.DiscoveryService;
import com.dempe.forest.common.discovery.NodeDetails;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.curator.framework.recipes.leader.Participant;
import org.apache.curator.x.discovery.ServiceInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Dempe
 * Date: 2016/4/8
 * Time: 13:09
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("discovery")
public class DiscoveryController {


    @Resource
    private DiscoveryService discoveryService;


    @RequestMapping("index")
    public String index() {
        return "/service/discovery";
    }

    /**
     * 当前服务是否主服务
     * @return
     */
    @RequestMapping("hasLeadership")
    @ResponseBody
    public boolean hasLeadership() {
        return discoveryService.hasLeadership();
    }

    @RequestMapping("listNodeByName")
    @ResponseBody
    private Collection<ServiceInstance<NodeDetails>> listNodeByName(@RequestParam String name) throws Exception {
        Collection<ServiceInstance<NodeDetails>> serviceInstances = discoveryService.listByName(name);
        return serviceInstances;
    }

    @RequestMapping("listAllNodes")
    @ResponseBody
    public Collection<NodeDetails> listAllNodes() throws Exception {
        List<Collection<ServiceInstance<NodeDetails>>> list = discoveryService.list();

        ArrayList<NodeDetails> nodeList = Lists.newArrayList();
        if (list != null && list.size() > 0) {
            for (Collection<ServiceInstance<NodeDetails>> serviceInstances : list) {
                if (serviceInstances.size() < 1) {
                    continue;
                }
                Collection<Participant> participants = discoveryService.getParticipants();
                Map<String, Boolean> leaderMap = Maps.newHashMap();
                for (Participant participant : participants) {
                    leaderMap.put(participant.getId(), participant.isLeader());
                }
                for (ServiceInstance<NodeDetails> serviceInstance : serviceInstances) {
                    NodeDetails payload = serviceInstance.getPayload();
                    payload.setLeader(leaderMap.get(payload.getId()));
                    nodeList.add(payload);
                }
            }

        }
        return nodeList;
    }


}
